package pers.cz.mock;

import pers.cz.config.Config;
import pers.cz.util.ICollectGenerator;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * 多线程录制接口出入参
 * @program: postgirl-collection-client
 * @description: InterfaceThread
 * @author: Cheng Zhi
 * @create: 2022-02-22 15:08
 **/
public class InterfaceThread implements ICollectGenerator {

    private String request;
    private String response;
    private Integer busiCode;
    private Jedis resource;
    private String traceId;

    public InterfaceThread(String request, String response, Integer busiCode, Jedis resource, String traceId) {
        this.request = request;
        this.response = response;
        this.busiCode = busiCode;
        this.resource = resource;
        this.traceId = traceId;
    }

    @Override
    public void run() {
        try {
            if (denialOfService()) {
                insertRedis(request, response, busiCode, traceId);
            }
        } finally {
            resource.close();
        }

    }

    /**
     * 插入redis
     * @param request
     * @param response
     * @param busiCode
     */
    private void insertRedis(String request, String response, Integer busiCode, String traceId) {
        try {

            Map<String, String> cacheMap = Config.getConfig().getsysConfig();
            String key = cacheMap.get("redis.CollectionQueue");
            String source = cacheMap.get("source");
            //resource.rpop(key);
            this.resource.lpush(key, source + "||" + busiCode + "||" + request + "||" + response + "||" + traceId);
        } catch (Exception e) {

        }
    }

    /**
     * 是否拒绝服务
     * @return
     */
    private boolean denialOfService(){
        try {
            Map<String, String> cacheMap = Config.getConfig().getsysConfig();
            String collectionSwitchKey = cacheMap.get("redis.collectionSwitch");
            // 如果redis中开关为关闭状态则不进行录制
            String redisSwitch = resource.get(collectionSwitchKey);
            if (redisSwitch.equals("0")) {
                return false;
            }
            Integer collectionCycle = Integer.valueOf(cacheMap.get("redis.collectionCycle"));
            Integer collectionCount = Integer.valueOf(cacheMap.get("redis.collectionCount"));
            String collectionKey = cacheMap.get("redis.collectionKey");
            Long incr = resource.incr(collectionKey);

            if (incr <=1) {
                resource.expire(collectionKey, collectionCycle);
            }
            if(incr <= collectionCount){
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }
}
